package com.doupi.partner.op.util;

import com.doupi.partner.dal.model.Administrator;
import com.doupi.partner.manager.AdministratorManager;
import com.doupi.partner.service.dto.AdministratorDto;
import com.doupi.partner.util.ObjectUtils;
import com.doupi.partner.util.SpringContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * op相关工具类
 * 
 * @author Alvin Wang
 * @version 1.0.0 @ 2017-04-16
 */
public class OpUtils {
	private final static String OP_CURRENT_USER = "OP_CURRENT_USER";

	/**
	 * 获取当前登录的用户
	 *
	 * @return {@link Administrator} 当前用户
	 */
	public static AdministratorDto getCurrentLoginAdministrator() {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		AdministratorDto administratorDto = (AdministratorDto) session.getAttribute(OP_CURRENT_USER);
		if (null == administratorDto) {
			Administrator administrator = (Administrator) subject.getPrincipal();
			if (null != administrator) {
				administratorDto = new AdministratorDto();
				ObjectUtils.copyProperties(administratorDto, administrator);
				SpringContextUtils.getBeanByClass(AdministratorManager.class).wrapAdministratorDtoWithRelation(administratorDto);
				session.setAttribute(OP_CURRENT_USER, administratorDto);
			}
		}
		return administratorDto;
	}

	/**
	 * 根据请求获取逼着
	 */
	public static String getBizFromRequest(ServletRequest servletRequest) {
		if (servletRequest instanceof HttpServletRequest) {
			HttpServletRequest httpServletRequest = ((HttpServletRequest) servletRequest);
			String servletPath = httpServletRequest.getServletPath();
			servletPath = StringUtils.substringAfter(servletPath, "/");
			return StringUtils.substringBefore(servletPath, "/");
		}
		return StringUtils.EMPTY;
	}
}
